package com.nanxhs.concurrent.timeunit;

import java.util.concurrent.TimeUnit;

/**
 * @author: haibin.tang
 * @date: 2020/8/13
 */
public class TimeUnitMain {

    public static void main(String[] args) {
        TimeUnitMain instance = new TimeUnitMain();
        instance.sleep();
        instance.waitTime();
    }

    /**
     * 测试睡眠
     */
    private  void sleep() {
        try {
            long startTime = System.currentTimeMillis();
            TimeUnit.SECONDS.sleep(1);
            System.out.println("睡眠了" + (System.currentTimeMillis() - startTime) / 1000 + "S");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试obj.wait
     */
    private void waitTime() {
        try {
            //Object.wait 方法必须要有锁才能进行等待
            synchronized (this) {
                long startTime = System.currentTimeMillis();
                TimeUnit.SECONDS.timedWait(this, 2);
                System.out.println("wait了" + (System.currentTimeMillis() - startTime) / 1000 + "S");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
